package com.leozhang.app;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

public class SSLUtil {

    public static void configureSSLConnection(HttpURLConnection conn) {
        try {
            // 使用 TLSv1.2 协议
            SSLContext sc = SSLContext.getInstance("TLSv1.2");

            // 定义一个只信任根证书的 TrustManager
            TrustManager[] trustManagers = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return null; // 可以根据需求返回受信任的证书颁发机构列表
                        }

                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                            // 这里可以实现客户端证书验证
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                            // 这里可以实现服务器证书验证
                        }
                    }
            };

            // 初始化 SSLContext，使用我们的 TrustManager
            sc.init(null, trustManagers, new java.security.SecureRandom());

            // 设置 HttpsURLConnection 使用这个 SSLSocketFactory
            ((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory());

            // 设置 HostnameVerifier 确保服务器的主机名与证书匹配
            // ((HttpsURLConnection) conn).setHostnameVerifier((hostname, session) -> true);
            // // 这里应该返回false，以确保验证主机名，生产中需要根据实际情况决定
            ((HttpsURLConnection) conn).setHostnameVerifier(new TrustAnyHostnameVerifier());

        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException("SSL configuration failed", e);
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            System.out.println("hostname: " + hostname + ", session: " + session);
            return true;
        }
    }

    public static void main(String[] args) throws IOException {
        URL url = new URL("https://192.168.60.50"); // 示例 URL
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 配置 SSL 设置
        configureSSLConnection(conn);

        // 发送请求
        conn.connect();
        // 处理响应
        System.out.println("Response Code: " + conn.getResponseCode());
        System.out.println("Response Message: " + conn.getResponseMessage());
    }
}
